import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Main from '../views/Main.vue'
import { ElMessage } from 'element-plus';

const routes = [

    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/',
        name: 'Main',
        component: Main
    },
    {
        path: '/main',
        name: 'MainAlt', // 可以使用不同的名称以区分不同路径指向同一组件的情况
        component: Main
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const authorization = localStorage.getItem('Authorization');
    if (to.name === 'Login') {
        // 如果是前往登录页面，直接放行
        next();
    } else if (!authorization) {
        ElMessage.error('未登录或登录已失效，请重新登录');
        next({ name: 'Login' });
    } else {
        next();
    }
});

export default router